package com.lagou.controller;

import com.lagou.dto.UserBuyProductMsg;
import com.lagou.entity.COrder;
import com.lagou.repository.COrderRepository;
import com.lagou.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

/**
 * @author mcl
 * @date 2021/10/4 14:13
 * @description
 */
@Slf4j
@RestController
public class OrderController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private ProductService productService;
    @Autowired
    private COrderRepository orderRepository;

    @GetMapping("/getProductCount")
    public Long getProductCount(@RequestParam(name = "productId")Long productId) {
        return productService.getCountById(productId);
    }

    @GetMapping("/incrementProductCount")
    public Long incrementProductCount(@RequestParam Long productId) {
        return productService.incrementProductCount(productId);
    }

    @GetMapping("/decrementProductCount")
    public Long decrementProductCount(@RequestParam Long productId) {
        return productService.decrementProductCount(productId);
    }

    /**
     * 秒杀商品
     * @param userBuyProductMsg
     * @return
     */
    @PostMapping("/quickBuy")
    public String quickBuy(@RequestBody UserBuyProductMsg userBuyProductMsg) {
        Long countById = productService.getCountById(userBuyProductMsg.getProductId());
        log.info("quickBuy: userBuyProductMsg->{},count->{}",userBuyProductMsg,countById);
        if (countById <=0) {
            return "failed";
        }
        // TODO: 2021/10/14 不管是同步发送，还是异步发送，消费者那边都必须要快速消费，消费速度有延迟，新的请求进来拿到的货品剩余数量是错误的
//        rocketMQTemplate.syncSendOrderly("quick_buy_product", MessageBuilder.withPayload(userBuyProductMsg).build(), userBuyProductMsg.toString());
        rocketMQTemplate.asyncSendOrderly("quick_buy_product", userBuyProductMsg, userBuyProductMsg.toString(), new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info(sendResult.toString()+","+userBuyProductMsg);
            }

            @Override
            public void onException(Throwable e) {
                log.error("quick_buy_product->error->",e);
            }
        });
        return "success";
    }

    /**
     * 支付订单
     * @param order
     * @return
     */
    @PostMapping("/payOrder")
    public String payOrder(@RequestBody COrder order) {
        Optional<COrder> byId = orderRepository.findById(order.getId());
        if (byId.isPresent()) {
            COrder cOrder = byId.get();
            if ("Paying".equals(cOrder.getStatus())) {
                log.info(cOrder.toString());
                cOrder.setStatus("Payed");
                orderRepository.save(cOrder);
                return "success";
            } else {
                return "failed";
            }
        } else {
            return "failed";
        }
    }
}
